import { expect } from 'chai';
import * as step from '@flow-step/step-toolkit'
import sinon from 'sinon';
import { deleteBranch } from '../src/deleteBranch';

const workDir = './workspace';
const myRepo = 'my-repo_LBTL';
const sources = JSON.stringify([
    {
        name: myRepo,
        data: {},
    },
]);

describe('deleteBranch', () => {
    let envStub: sinon.SinonStub;
    let git: any;
    let stepInfoStub: sinon.SinonStub;
    let stepErrorStub: sinon.SinonStub;
    beforeEach(() => {
        envStub = sinon.stub(process, 'env')
        stepInfoStub = sinon.stub(step, 'info');
        stepErrorStub = sinon.stub(step, 'error');
        git = {
            push: sinon.stub().resolves()
        }
    });

    afterEach(() => {
        sinon.restore();
    });

    it('should skip deleting if the source branch is the same as the target branch', async () => {
        envStub.value({'PROJECT_DIR': `${workDir}/${myRepo}`,
            'SOURCES': sources,
            'TARGET_BRANCH': 'f1',
        });

        await deleteBranch(git,'f1');
        expect(stepInfoStub.calledWith('Current branch f1 is the same as the target branch f1, skip deleting.')).to.be.true;
        expect(git.push.notCalled).to.be.true;
    });

    it('should delete the source branch if it is different with the target branch', async () => {
        envStub.value({'PROJECT_DIR': `${workDir}/${myRepo}`,
            'SOURCES': sources,
            'TARGET_BRANCH': 'master',
        });

        await deleteBranch(git, 'feature-branch');

        expect(git.push.calledWith('origin', 'feature-branch', ['--delete'])).to.be.true;
        expect(stepInfoStub.calledWith(`branch feature-branch was successfully deleted`)).to.be.true;
})

    it('should throw an error if the branch does not exist', async () => {
        envStub.value({'PROJECT_DIR': `${workDir}/${myRepo}`,
            'SOURCES': sources,
            'TARGET_BRANCH': 'master',
        });

        git.push.rejects(new Error('Branch not found'));

        try {
            await deleteBranch(git, 'feature-branch');
        } catch (error:any) {
            expect(error.message).to.equal('Branch not found');
            expect(stepErrorStub.calledWith('failed to delete branch feature-branch')).to.be.true;
        }
    })
});
